
package com.kim.pong.router

import com.kim.pong.service.PongService
import org.spockframework.spring.SpringBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.test.web.reactive.server.WebTestClient
import org.springframework.web.reactive.function.server.RouterFunction
import org.springframework.web.reactive.function.server.ServerResponse
import spock.lang.Specification

import static org.springframework.http.MediaType.APPLICATION_JSON

@Configuration
class PongRouterSpec extends Specification {

    @SpringBean
    PongService pongService = Mock()

    PongRouter router = new PongRouter()

    WebTestClient webTestClient

    def setup() {
        RouterFunction<ServerResponse> route = router.route(pongService)
        webTestClient = WebTestClient.bindToRouterFunction(route).build()
    }

    def "GET /pong should call handlePing method of PongService"() {
        given:
        def expectedResponse = "Pong"

        when:
        webTestClient.get()
                .uri("/pong")
                .accept(APPLICATION_JSON)
                .exchange()

        then:
        1 * pongService.handlePing(_) >> ServerResponse.ok().bodyValue(expectedResponse)
    }

    def "GET /pong should return 200 OK with correct response body"() {
        given:
        def expectedResponse = "Pong"
        pongService.handlePing(_) >> ServerResponse.ok().bodyValue(expectedResponse)

        when:
        def response = webTestClient.get()
                .uri("/pong")
                .accept(APPLICATION_JSON)
                .exchange()

        then:
        response.expectStatus().isOk()
        response.expectBody(String.class).isEqualTo(expectedResponse)
    }
}